<?php
session_start();

$error = '';



// 处理表单登录提交
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['login'])) {

    //连接数据库
    $servername = "localhost";
    $mysqluser = "root";
    $dbpass = "mysql123456";
    $dbname = "student";
    try {
        $conn = new PDO("mysql:host=$servername;dbname=$dbname", $mysqluser, $dbpass,array(
            PDO::ATTR_PERSISTENT => true
        ));
        // $error = '连接成功'; 
    }
    catch(PDOException $e)
    {
        $error = '数据库连接失败: ' . $e->getMessage();
    }

    $username = trim($_POST['username']);
    $password = trim($_POST['password']);
    
    
   // 验证用户名和密码
    try {
        // 设置PDO错误模式为异常
        $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
        $conn->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);

        // 根据id查询用户
        $stmt = $conn->prepare("SELECT id, passwd, name FROM `2402` WHERE id = :id LIMIT 1");
        $stmt->bindValue(':id', $username, is_numeric($username) ? PDO::PARAM_INT : PDO::PARAM_STR);
        $stmt->execute();
        $user = $stmt->fetch(PDO::FETCH_ASSOC);

        if (!$user) {
            $error = '用户不存在';
        } else {
            // 验证密码（假设passwd字段存储的是哈希值）
            if ($password == $user['passwd']) {
                
                $_SESSION['is_login'] = 1;
                $_SESSION['username'] = $user['name'];
                // 登录成功后重置尝试次数
                $_SESSION['attempts'] = 0;
                $_SESSION['user_id'] = $user['id'];
                
                // 记住我功能处理 未做
                if (isset($_POST['remember'])) {
                    $token = bin2hex(random_bytes(32));
                    // 更新数据库token字段（需要添加remember_token字段）
                    $updateStmt = $conn->prepare("UPDATE users SET remember_token = ? WHERE id = ?");
                    $updateStmt->execute([$token, $user['id']]);
                    setcookie('remember_token', $token, time()+86400*30, '/');
                }
                
                $conn=null; // 关闭数据库连接
                header('Location: index.php');
                exit;
            } else {
                $error = '密码错误';
            }
    }
} catch(PDOException $e) {
    error_log("登录验证错误: " . $e->getMessage());
    $error = '系统错误，请稍后再试';
}
}



// 记录失败尝试
$_SESSION['attempts'] = ($_SESSION['attempts'] ?? 0) + 1;
if ($_SESSION['attempts'] > 20) {
    // die('请5分钟后再试');
}
// 验证失败时存储错误并跳转回登录页
    $_SESSION['login_error'] = $error;
    header('Location: blog_login.php');
    exit;
?>